package com.openroom.ui.component;

import java.awt.image.BufferedImage;
import java.net.URL;

import org.apache.log4j.Logger;
import org.apache.pivot.collections.Map;
import org.apache.pivot.util.Resources;
import org.apache.pivot.wtk.CardPane;
import org.apache.pivot.wtk.TablePane;
import org.apache.pivot.wtk.media.Picture;

import com.jphotomanager.io.ImageLibrary;
import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventHandler;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.model.ModelLocator;
import com.openroom.model.ModelLocator.ModeFlag.ImageViewMode;
import com.openroom.model.Photograph;
import com.openroom.ui.PreviewImageView;

public class PreviewImagePane extends TablePane {
    private static final Logger LOGGER = Logger
            .getLogger(PreviewImagePane.class);

    private final class PreviewEventHandler implements EventHandler {
        @Override
        public void handle(ApplicationEvent event1) {
            if (!ModelLocator.getInstance().getCurrentImageMode()
                    .equals(ImageViewMode.PREVIEW))
                return;
            Photograph p = ModelLocator.getInstance()
                    .getCurrentlySelectedImage();
            if (p == null)
                return;
            try {
                BufferedImage displayImage = ImageLibrary.getInstance()
                        .getDisplayImage();
                previewImage.setPreviewImage(new Picture(displayImage));
            } catch (Exception e) {
                LOGGER.error("error",e);
            }
        }
    }

    private CardPane cardPane;

    private PreviewImageView previewImage;

    public PreviewImagePane() {

    }

    public void initialize(Map<String, Object> namespace, URL arg1,
            Resources arg2) {
        cardPane = (CardPane) namespace.get("cardPane");
        previewImage = (PreviewImageView) namespace.get("previewImage");
        EventManager.getInstance().listenToEventType(new PreviewEventHandler(),
                EventType.CURRENT_IMAGE_CHANGED, EventType.VIEW_MODE_CHANGED);
    }
}
